//
//  YZYSDKManager.m
//  YZYSDKManagerDemo
//
//  Created by 赵隆杰 on 2024/6/7.
//

#import "YZYSDKManager.h"

#import "YZYActivityView.h"
#import "YZYAlertView.h"
#import "YZYBindPhoneView.h"
#import "YZYLoginView.h"
#import "YZYRealNameAuthenticationView.h"
#import "YZYSonUserListView.h"
#import "YZYSuspendManager.h"
#import "BDASignalManager.h"
#import "BDASignalDefinitions.h"

#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/ASIdentifierManager.h>
#import <AdServices/AdServices.h>

#import "IPAPurchase.h"

#import "YZYPlatformLoginManager.h"
#import "ZCFunDataFormat.h"
#import "YZYSaccountStore.h"
#import "YZYUserInfo.h"
#import "ZCNetworkManager.h"
#import "YZYNetworkManager.h"
#import "YZYUUID.h"
#import "YZYSDKManagerHeader.h"

@interface YZYSDKManager ()<YZYPlatformLoginDelegte>

@property (nonatomic ,weak) id <YZYSDKManagerDelegate> delegate;

@property (nonatomic, copy) NSString *userId;
@property (nonatomic, copy) NSString *sonUserId;

@property (nonatomic, strong) YZYRoleInfo *currentRoleInfo;

@property (nonatomic, strong) NSDictionary *yzy_launchOptions;

@property (nonatomic, assign) int init_idfa; //获取idfa标记(无论是否获取到，获取过了，努力过了，就算)

@end

@implementation YZYSDKManager

/**
 单例模式

 @return YZYSDKManager
 */
+ (instancetype)shareManager {
    static YZYSDKManager *shareManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareManager = [[YZYSDKManager alloc] init];
    });
    return shareManager;
}

- (instancetype)init {
    if (self = [super init]) {
    }
    return self;
}

/**
 设置监听
 */
- (void)yzy_sdkManagerListener:(id)sdkManagerListener {
    NSLog(@"yzysdk - yzy_sdkManagerListener");
    [YZYSDKManager shareManager].delegate = sdkManagerListener;
}
/**
 显示登录按钮
 */
- (void)yzy_showLoginUI {
    if ([[ZCFunDataFormat GetPlatformGameID] length] == 0) {
        [[YZYSaccountStore sharedInstance] makeToastFromWindow:@"请在YZYPLIST.h中设置SDK_GAME_ID"];
        return;
    }
    //移除sdk UI
    [[YZYSaccountStore sharedInstance] getCurrentWindowWithCompletion:^(UIWindow *window) {
        if (window) {
            for (UIView *subview in window.subviews) {
                if ([subview isKindOfClass:NSClassFromString(@"YZYActivityView")]) {
                    YZYActivityView *activityView = (YZYActivityView *)subview;
                    [activityView closeView];
                }
                if ([subview isKindOfClass:NSClassFromString(@"YZYAlertView")]) {
                    YZYAlertView *alertView = (YZYAlertView *)subview;
                    [alertView closeView];
                }
                if ([subview isKindOfClass:NSClassFromString(@"YZYBindPhoneView")]) {
                    YZYBindPhoneView *bindPhoneView = (YZYBindPhoneView *)subview;
                    [bindPhoneView closeView];
                }
                if ([subview isKindOfClass:NSClassFromString(@"YZYLoginView")]) {
                    YZYLoginView *loginView = (YZYLoginView *)subview;
                    [loginView closeView];
                }
                if ([subview isKindOfClass:NSClassFromString(@"YZYRealNameAuthenticationView")]) {
                    YZYRealNameAuthenticationView *realNameAuthenticationView = (YZYRealNameAuthenticationView *)subview;
                    [realNameAuthenticationView closeView];
                }
                if ([subview isKindOfClass:NSClassFromString(@"YZYSonUserListView")]) {
                    YZYSonUserListView *sonUserListView = (YZYSonUserListView *)subview;
                    [sonUserListView closeView];
                }
            }
        }
    }];
    [YZYPlatformLoginManager shareLoginManager].delegate = self;
    NSString* accessToken = [[YZYSaccountStore sharedInstance] getAccessToken];
    if (![ZCFunDataFormat isBlankString:accessToken]) {
        //直接登录
        [[YZYPlatformLoginManager shareLoginManager] getUserByToken];
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [[YZYPlatformLoginManager shareLoginManager] showLoginViewUI];
    });
}

#pragma mark - YZYPlatformLoginDelegte
- (void)phoneLoginBack:(PlatformResultType)type msg:(NSString *)msg userInfo:(id)userInfo {
    if (type == PlatformResultSuccess) {
        NSLog(@"平台登录完成");
		self.isLogin = YES;//标记已登录
        if (![userInfo isKindOfClass:[YZYUserInfo class]]) {
            NSLog(@"平台登录用户信息为空");
            return;
        }
        YZYUserInfo *userInfo_ = (YZYUserInfo *)userInfo;
        self.userId = [userInfo_.userId stringValue];
        self.sonUserId = [userInfo_.sonId stringValue];
        if ([[YZYSaccountStore sharedInstance] getIsScoreOpen]) {
            //显示公告
            [self showActivity];
        }
        //用户行为上报
        [self userReportWithUserInfo:userInfo_];
        
        //回调外部进行游戏操作
        NSDictionary *result = @{
            @"uid": userInfo_.sonId,
            @"token": [YZYSaccountStore sharedInstance].getAccessToken
        };
        NSLog(@"yzysdk - phoneLoginBack");
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([self.delegate respondsToSelector:@selector(yzy_LoginCallBack:data:)]) {
                [self.delegate yzy_LoginCallBack:1 data:result];
            }
        });
    } else if (type == PlatformResultChangeAccount) {
        NSLog(@"切换账号");
		self.isLogin = NO;//标记未登录
        NSString* accessToken = [[YZYSaccountStore sharedInstance] getAccessToken];
        if (![ZCFunDataFormat isBlankString:accessToken]) {
            //先进行账号退出操作，再重新调起登录
            NSLog(@"先自行账号退出操作，再重新调起登录");
            typeof(self) __weak weakSelf = self;
            [self logoutPlatformCompleteHandle:^(BOOL logoutPlatformSuccess) {
                if (logoutPlatformSuccess) {
                    [weakSelf yzy_showLoginUI];
                }
            }];
        } else {
            //token都没有，直接调出登录页
            NSLog(@"token都没有，直接调出登录页");
            //清除登录信息
            [[YZYSaccountStore sharedInstance] removeAccessToken];
            [[YZYSaccountStore sharedInstance] removeUserInfoStr];
            [[YZYSaccountStore sharedInstance] removeUserIdentifier];
            self.userId = @"";
            self.sonUserId = @"";
            self.currentRoleInfo = nil;
            
            [self yzy_showLoginUI];
        }
        
        
    } else {
        //登录失败，重新调起登录
        NSLog(@"登录失败，重新调起登录");
        [self phoneLoginBack:PlatformResultChangeAccount msg:@"登录失败，重新调起登录" userInfo:@""];
    }
}

#pragma mark - 退出登录
- (void)platformAccountLogoutCompleteHandle:(void(^)(BOOL loginOutSuccess))loginOutHandle {
    NSDictionary *params = @{};
    [ZCNetworkManager postWithURL:YZY_AppendUrl(YZY_loginOut) Params:params success:^(id responseObject) {
        NSDictionary *surperdic = (NSDictionary *)responseObject;
        NSString *surpercode = [NSString stringWithFormat:@"%@",surperdic[@"code"]];
//        NSString *msg = [NSString stringWithFormat:@"%@",surperdic[@"msg"]];
        if ([surpercode isEqualToString:@"200"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //清除登录信息
                [[YZYSaccountStore sharedInstance] removeAccessToken];
                [[YZYSaccountStore sharedInstance] removeUserInfoStr];
                [[YZYSaccountStore sharedInstance] removeUserIdentifier];
                self.userId = @"";
                self.sonUserId = @"";
                self.currentRoleInfo = nil;
                [[YZYSuspendManager sharedInstance] WebSocketClose];
                loginOutHandle(YES);
            });
        } else {
            loginOutHandle(NO);
        }
    } failure:^(NSString *error) {
        loginOutHandle(NO);
    }];
}
#pragma mark - 删除账号
- (void)platformAccountDeleteCompleteHandle:(void(^)(BOOL loginDeleteSuccess))loginDeleteHandle {
    NSDictionary *params = @{};
    [ZCNetworkManager postWithURL:YZY_AppendUrl(YZY_deleteUser) Params:params success:^(id responseObject) {
        NSDictionary *surperdic = (NSDictionary *)responseObject;
        NSString *surpercode = [NSString stringWithFormat:@"%@",surperdic[@"code"]];
//        NSString *msg = [NSString stringWithFormat:@"%@",surperdic[@"msg"]];
        if ([surpercode isEqualToString:@"200"]) {
            loginDeleteHandle(YES);
        } else {
            loginDeleteHandle(NO);
        }
    } failure:^(NSString *error) {
        loginDeleteHandle(NO);
    }];
}

#pragma mark - 游戏活动公告
- (void)showActivity {
    NSString *url = [NSString stringWithFormat:@"%@/%@", YZY_getNoticeList, [ZCFunDataFormat GetPlatformGameID]];
    [ZCNetworkManager getWithURL:YZY_AppendUrl(url) Params:nil success:^(id responseObject) {
        NSDictionary *surperdic = (NSDictionary *)responseObject;
        NSString *surpercode = [NSString stringWithFormat:@"%@",surperdic[@"code"]];
//        NSString *msg = [NSString stringWithFormat:@"%@",surperdic[@"msg"]];
        if ([surpercode isEqualToString:@"200"]) {
            NSNumber *isShow = [ZCFunDataFormat filterNumber:surperdic[@"isShow"]];
            if (isShow.boolValue) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSString *h5Url = [NSString stringWithFormat:@"%@/gameNotice/%@", YZY_H5_BaseUrl, [ZCFunDataFormat GetPlatformGameID]];
                    YZYActivityView *activityView = [[YZYActivityView alloc] init];
                    activityView.urlTitle = @"游戏活动公告";
                    activityView.h5Url = h5Url;
                    [activityView show];
                });
            }
        }
    } failure:^(NSString *error) {
        
    }];
    
    
}
#pragma mark - 用户行为上报
- (void)userReportWithUserInfo:(YZYUserInfo *)userInfo {
    int randomNumber = arc4random_uniform(128) + 1;//1到128随机数
    NSNumber *bt = @1;
    NSNumber *ct = userInfo.isAuth.boolValue ? @0 : @2;
    NSString *di = userInfo.uuid;
    NSString *no = [NSString stringWithFormat:@"%d", randomNumber];
    NSString *ot = [ZCFunDataFormat getNowTimeTimestamp];
//    NSString *pi = @"";
    NSString *md5str = [NSString stringWithFormat:@"%@%@%@%@",[ZCFunDataFormat GetPlatformGameID],ot,no,YZYKey];
    NSString *si = [ZCFunDataFormat ZCMD5WithNSString:md5str];
    NSString *idfv = [YZYUUID uuidForIDFV];
    NSString *idfa = [YZYUUID uuidForIDFA];
    
    NSDictionary *params = @{
        @"bt": bt,//游戏用户行为类型 0下线 1上线
        @"ct": ct,//上报类型 0已认证通过用户 2游客用户
        @"di": di,//设备标识
        @"no": no,//条目编码
        @"ot": ot,//行为发生时间
//        @"pi": pi,//用户唯一标识，不用传
        @"si": si,//游戏内部会话标识
        @"gameId": [ZCFunDataFormat GetPlatformGameID],
        @"sonUserId": userInfo.sonId,
        @"idfv": idfv,
        @"idfa": idfa
    };
    [ZCNetworkManager postWithURL:YZY_AppendUrl(YZY_userBehaviorReport) Params:params success:^(id responseObject) {
        NSDictionary *surperdic = (NSDictionary *)responseObject;
        NSString *surpercode = [NSString stringWithFormat:@"%@",surperdic[@"code"]];
//        NSString *msg = [NSString stringWithFormat:@"%@",surperdic[@"msg"]];
        if ([surpercode isEqualToString:@"200"]) {
            
        }
    } failure:^(NSString *error) {
        
    }];
}

#pragma mark - 提交角色信息
/**
 提交角色信息
 */
- (void)yzy_submitRoleInfo:(YZYRoleInfo *)roleInfo {
    
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970];// *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    NSString *login_time = @"";
    NSString *loginout_time = @"";
    NSString *reg_time = @"";
    NSString *update_time = @"";
    if ([roleInfo.role_type isEqualToString:@"enterserver"]) {
        login_time = timeString;
    } else if ([roleInfo.role_type isEqualToString:@"createrole"]) {
        reg_time = timeString;
    } else if ([roleInfo.role_type isEqualToString:@"levelup"]) {
        update_time = timeString;
    } else {
        loginout_time = timeString;
    }
    roleInfo.login_time = login_time;
    roleInfo.reg_time = reg_time;
    roleInfo.update_time = update_time;
    roleInfo.loginout_time = loginout_time;
    
    [self submitRoleInfo1:roleInfo completeHandle:^(BOOL roleInfoSuccess) {
        if (roleInfoSuccess) {
            NSLog(@"角色上报成功");
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([self.delegate respondsToSelector:@selector(yzy_updateRoleCallBack:)]) {
                    [self.delegate yzy_updateRoleCallBack:@{@"status":@"success"}];
                }
            });
            if ([[YZYSaccountStore sharedInstance] getIsScoreOpen]) {
                //开启长链接
                [[YZYSuspendManager sharedInstance] props_roleUpdateWithRoleModel:roleInfo];
            }
        }
    }];
}
- (void)submitRoleInfo1:(YZYRoleInfo *)roleInfo completeHandle:(void(^)(BOOL roleInfoSuccess))roleInfoHandle {
    if ([self checkEmptyRoleInfo:roleInfo]) return;
    roleInfo.user_id = self.userId;
    roleInfo.son_user_id = self.sonUserId;
    self.currentRoleInfo = roleInfo;
    [self submitRoleInfoWithDict:[self commonRoleInfo:roleInfo] completeHandle:^(BOOL isSuccess) {
        roleInfoHandle(isSuccess);
    }];
}
- (BOOL)checkEmptyRoleInfo:(YZYRoleInfo *)roleInfo {
    if ([ZCFunDataFormat isBlankString:roleInfo.role_type]) {
        [[YZYSaccountStore sharedInstance] makeToastFromWindow:@"角色类型为空"];
        return YES;
    }
    if ([roleInfo.role_type isEqualToString:@"enterserver"] && [ZCFunDataFormat isBlankString:roleInfo.login_time]) {
        [[YZYSaccountStore sharedInstance] makeToastFromWindow:@"登录时间为空"];
        return YES;
    }
    if ([roleInfo.role_type isEqualToString:@"loginout"] && [ZCFunDataFormat isBlankString:roleInfo.loginout_time]) {
        [[YZYSaccountStore sharedInstance] makeToastFromWindow:@"登出时间为空"];
        return YES;
    }
    if ([roleInfo.role_type isEqualToString:@"createrole"] && [ZCFunDataFormat isBlankString:roleInfo.reg_time]) {
        [[YZYSaccountStore sharedInstance] makeToastFromWindow:@"注册时间为空"];
        return YES;
    }
    if ([roleInfo.role_type isEqualToString:@"levelup"] && [ZCFunDataFormat isBlankString:roleInfo.update_time]) {
        [[YZYSaccountStore sharedInstance] makeToastFromWindow:@"更新时间为空"];
        return YES;
    }
    if ([ZCFunDataFormat isBlankString:roleInfo.role_id]) {
        [[YZYSaccountStore sharedInstance] makeToastFromWindow:@"角色ID为空"];
        return YES;
    }
    if ([ZCFunDataFormat isBlankString:roleInfo.role_level]) {
        [[YZYSaccountStore sharedInstance] makeToastFromWindow:@"角色等级为空"];
        return YES;
    }
    if ([ZCFunDataFormat isBlankString:roleInfo.role_name]) {
        [[YZYSaccountStore sharedInstance] makeToastFromWindow:@"角色名称为空"];
        return YES;
    }
    if ([ZCFunDataFormat isBlankString:roleInfo.service_id]) {
        [[YZYSaccountStore sharedInstance] makeToastFromWindow:@"区服ID为空"];
        return YES;
    }
    if ([ZCFunDataFormat isBlankString:roleInfo.service_name]) {
        [[YZYSaccountStore sharedInstance] makeToastFromWindow:@"区服名称为空"];
        return YES;
    }
    return NO;
}
- (NSMutableDictionary *)commonRoleInfo:(YZYRoleInfo *)roleInfo {
    NSMutableDictionary *roleInfoDict = [[NSMutableDictionary alloc] init];
    roleInfoDict[@"roleId"] = roleInfo.super_role_id;//这里传平台角色id
    roleInfoDict[@"roleLevel"] = roleInfo.role_level;
    roleInfoDict[@"roleName"] = roleInfo.role_name;
    roleInfoDict[@"serviceId"] = roleInfo.service_id;
    roleInfoDict[@"serviceName"] = roleInfo.service_name;
    roleInfoDict[@"description"] = [ZCFunDataFormat isBlankString:roleInfo.describe] ? @"description" : roleInfo.describe;
    roleInfoDict[@"experience"] = [ZCFunDataFormat isBlankString:roleInfo.experience] ? @"1" : roleInfo.experience;
    roleInfoDict[@"money"] = [ZCFunDataFormat isBlankString:roleInfo.money] ? @"1" : roleInfo.money;
    roleInfoDict[@"gameId"] = [ZCFunDataFormat GetPlatformGameID];
    if (![ZCFunDataFormat isBlankString:roleInfo.login_ip]) {
        roleInfoDict[@"loginIp"] = roleInfo.login_ip;
    }
    if (![ZCFunDataFormat isBlankString:roleInfo.login_time]) {
        roleInfoDict[@"loginTime"] = roleInfo.login_time;
    }
    if (![ZCFunDataFormat isBlankString:roleInfo.loginout_time]) {
        roleInfoDict[@"loginoutTime"] = roleInfo.loginout_time;
    }
    roleInfoDict[@"osType"] = @"2";
    roleInfoDict[@"platformId"] = YZYPlatformID;//
    if (![ZCFunDataFormat isBlankString:roleInfo.reg_ip]) {
        roleInfoDict[@"regIp"] = roleInfo.reg_ip;
    }
    if (![ZCFunDataFormat isBlankString:roleInfo.reg_time]) {
        roleInfoDict[@"regTime"] = roleInfo.reg_time;
    }
    if (![ZCFunDataFormat isBlankString:roleInfo.role_label_code]) {
        roleInfoDict[@"roleLabelCode"] = roleInfo.role_label_code;
    }
    roleInfoDict[@"sonUserId"] = roleInfo.son_user_id;
    roleInfoDict[@"superUserId"] = roleInfo.super_user_id;
    if (![ZCFunDataFormat isBlankString:roleInfo.update_time]) {
        roleInfoDict[@"updateTime"] = roleInfo.update_time;
    }
    NSLog(@"roleInfoDict - %@", roleInfoDict);
    return roleInfoDict;
}
- (void)submitRoleInfoWithDict:(NSMutableDictionary *)roleInfoDict completeHandle:(void(^)(BOOL isSuccess))handle {
    NSDictionary *params = [roleInfoDict copy];
    [ZCNetworkManager postWithURL:YZY_AppendUrl(YZY_addRoleInfo) Params:params success:^(id responseObject) {
        NSDictionary *surperdic = (NSDictionary *)responseObject;
        NSString *surpercode = [NSString stringWithFormat:@"%@",surperdic[@"code"]];
//        NSString *msg = [NSString stringWithFormat:@"%@",surperdic[@"msg"]];
        if ([surpercode isEqualToString:@"200"]) {
            handle(YES);
        } else {
            handle(NO);
        }
    } failure:^(NSString *error) {
        handle(NO);
    }];
}
#pragma mark -  跳转小程序
- (void)yzy_jump_miniPrograms {
    NSLog(@"yzy_jump_miniPrograms");

    NSString *url_scheme = [NSString stringWithFormat:@"weixin://dl/business/?appid=%@&path=%@&query=id=%@&super_user_id=%@", [YZYNetworkManager shareManager].wx_appid, [YZYNetworkManager shareManager].wx_path, [ZCFunDataFormat GetQPGameID], self.currentRoleInfo.super_user_id];
    NSLog(@"yzysdk - url_scheme %@", url_scheme);
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:url_scheme]]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url_scheme] options:@{} completionHandler:^(BOOL success) {
            if (success) {
                NSLog(@"yzysdk - 打开小程序成功");
            } else {
                NSLog(@"yzysdk - 打开小程序失败");
            }
        }];
    }
    
}
#pragma mark -  退出登录
- (void)yzy_logoutPlatform {
    [self logoutPlatformCompleteHandle:^(BOOL logoutPlatformSuccess) {
        if (logoutPlatformSuccess) {
            self.isLogin = NO;
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"退出登录成功");
                //重新调起登录
                [self yzy_showLoginUI];
                //回调给游戏做游戏退出操作
                if ([self.delegate respondsToSelector:@selector(yzy_appleChangeAccountOrLogoutCallBack:)]) {
                    [self.delegate yzy_appleChangeAccountOrLogoutCallBack:@"退出登录成功"];
                }
            });
        }
    }];
}
- (void)logoutPlatformCompleteHandle:(void(^)(BOOL logoutPlatformSuccess))logoutPlatformHandle {
    if (self.currentRoleInfo) {
        //角色登出
        YZYRoleInfo *tmpRoleInfo = [YZYRoleInfo copyWithRoleInfo:self.currentRoleInfo];
        tmpRoleInfo.role_type = @"loginout";
        tmpRoleInfo.loginout_time = [[YZYSaccountStore sharedInstance] currentTimeStr];
        [self submitRoleInfo1:tmpRoleInfo completeHandle:^(BOOL roleInfoSuccess) {
            if (roleInfoSuccess) {
                //调用退出接口
                [self platformAccountLogoutCompleteHandle:^(BOOL isSuccess) {
                    if (isSuccess) {
                        logoutPlatformHandle(isSuccess);
                    } else {
                        logoutPlatformHandle(NO);
                    }
                }];
            } else {
                logoutPlatformHandle(NO);
            }
        }];
    } else {
        //直接调用退出接口
        [self platformAccountLogoutCompleteHandle:^(BOOL isSuccess) {
            if (isSuccess) {
                logoutPlatformHandle(isSuccess);
            } else {
                logoutPlatformHandle(NO);
            }
        }];
    }
    
}

#pragma mark -  删除账号
- (void)yzy_logoutPlatformForAccountDelete {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"删除账号后账户信息被清除且不可恢复，您确定要删除吗" preferredStyle:UIAlertControllerStyleAlert];
    //添加取消按钮
    UIAlertAction* cancelBtn = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
    }];
    //添加确定按钮
    UIAlertAction* confirmBtn = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        [self platformAccountDeleteCompleteHandle:^(BOOL loginDeleteSuccess) {
            if (loginDeleteSuccess) {
                [self yzy_logoutPlatform];
            }
        }];
    }];
    [alert addAction:cancelBtn];
    [alert addAction:confirmBtn];
    //显示
    [[YZYSaccountStore sharedInstance] getCurrentWindowWithCompletion:^(UIWindow *window) {
        if (window) {
            UIViewController *curViewController = window.rootViewController;
            [curViewController presentViewController:alert animated:YES completion:nil];
        }
    }];
}

#pragma mark - 支付
/**
 苹果支付
 @param goodID 产品ID
 @param payMoney 金额
 @param gameOrderSn 订单号
 @param remark 透传参数
*/
- (void)yzy_applePayWithGoodID:(NSString *)goodID PayMoney:(NSString *)payMoney gameOrderSn:(NSString *)gameOrderSn remark:(NSString *)remark {
    
    [[YZYNetworkManager shareManager] requestPlatformOrderInfoCreateOrderWithPayMoney:payMoney gameOrderSn:gameOrderSn remark:remark sonUserId:self.sonUserId userId:self.userId roleInfo:self.currentRoleInfo completeBlock:^(id  _Nonnull data) {
        NSDictionary *surperdic = (NSDictionary *)data;
        NSString *orderNo = [NSString stringWithFormat:@"%@",surperdic[@"orderNo"]];
        
        [[YZYNetworkManager shareManager] requestBillingPointMappingWithGoodID:goodID Success:^(NSDictionary * _Nonnull resultDict) {
            NSString *purchase_goodID = [NSString stringWithFormat:@"%@",resultDict[@"goodId"]];
            //支付计费点验证
            [[YZYNetworkManager shareManager] requestIosPayVerifyWithGoodID:purchase_goodID chooseEnv:@0 orderNo:orderNo receipt:@"" completeBlock:^(id  _Nonnull data) {
                [IPAPurchase manager].userid = self.userId;
                [IPAPurchase manager].orderNumber = orderNo;
                [[IPAPurchase manager] buyProductWithProductID:purchase_goodID payResult:^(BOOL isSuccess, NSString * _Nullable certificate, NSString * _Nullable errorMsg) {
                    if (isSuccess) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            if ([self.delegate respondsToSelector:@selector(yzy_applePayCallBack:data:)]) {
                                [self.delegate yzy_applePayCallBack:1 data:data];
                            }
                        });
                        
                    } else {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            if ([self.delegate respondsToSelector:@selector(yzy_applePayCallBack:data:)]) {
                                [self.delegate yzy_applePayCallBack:2 data:errorMsg];
                            }
                        });
                    }
                }];
            }];
        } failure:^(NSString * _Nonnull error) {
            
        }];
    }];
    
}

#pragma mark - UIApplicationDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.yzy_launchOptions = launchOptions;
    
    //不需要网络的初始化可以直接放这里，需要网络的初始化操作放在yzy_AfterNerwork_init
    
    return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
}
- (void)applicationDidBecomeActive:(UIApplication*)application {
    [self initAds];
}
- (void)applicationWillTerminate:(UIApplication *)application {
    [[IPAPurchase manager] stopManager];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo {
}
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    if ([ZCFunDataFormat GetIsLandscape]) {
        return UIInterfaceOrientationMaskLandscape;
    }
    return UIInterfaceOrientationMaskPortrait;
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    // 将url参数转换成string类型之后，传递给SDK
    NSString *openUrl = url.absoluteString;
    [BDASignalManager anylyseDeeplinkClickidWithOpenUrl:openUrl];
    return YES;
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return YES;
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return YES;
}
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray * restorableObjects))restorationHandler {
    return YES;
}


/**
 在有网络后的一些初始化操作
 */
- (void)yzy_AfterNerwork_init {
    NSLog(@"yzysdk - yzy_AfterNerwork_init");
    [self isAppleVersion];
    
    //初始化接口
    [self yzysdk_init];
    
    [[IPAPurchase manager] startManager];
    
    [[YZYNetworkManager shareManager] requestWechatGetInfoSuccess:^(NSDictionary * _Nonnull resultDict) {
        
    } failure:^(NSString * _Nonnull error) {
        
    }];
    
}

- (void)initBDASignalManager {
    NSLog(@"yzysdk - initBDASignalManager");
    
    if (self.init_idfa == 1) {
        return;
    }
    
    self.init_idfa = 1;
    
    NSString *idfv = [YZYUUID uuidForIDFV];
    NSString *idfa = [YZYUUID uuidForIDFA];
    NSLog(@"yzysdk - idfv:%@ idfa:%@", idfv, idfa);
        
    // 上报冷启动事件
    [BDASignalManager didFinishLaunchingWithOptions:self.yzy_launchOptions connectOptions:nil];
    // 注册可选参数
    [BDASignalManager registerWithOptionalData:@{
//        kBDADSignalSDKUserUniqueId : @""  // 业务用户id，非必传
    }];
    [BDASignalManager enableIdfa:YES];
    // 开启延时上报
    [BDASignalManager enableDelayUpload];
    // 允许数据上报
    [BDASignalManager startSendingEvents];
    [BDASignalManager getClickId];
    
}

- (void)initAds {
      UIApplication *applicaiton = [UIApplication sharedApplication];

    if (applicaiton.applicationState == UIApplicationStateActive)
    {
        if (@available(iOS 14, *)) {
            ATTrackingManagerAuthorizationStatus status = [ATTrackingManager trackingAuthorizationStatus];
            if(status == ATTrackingManagerAuthorizationStatusNotDetermined){
                [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
                    // Tracking authorization completed. Start loading ads here.

                    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                        [self initBDASignalManager];
                    }];
                }];
            }else{
                [self initBDASignalManager];
            }
        }else{
            // Fallback on earlier versions
            [self initBDASignalManager];
        }
    }else{
        [self performSelector:@selector(initAds)
                       withObject:nil
                       afterDelay:0.5f];
    }
}

- (void)yzysdk_init {
    NSLog(@"yzysdk - yzysdk_init");
    
    if (self.init_idfa == 1) {
        NSString *token = @"";
        if (@available(iOS 14.3, *)) {
            NSError *error;
            token = [AAAttribution attributionTokenWithError:&error];
        }
        NSLog(@"yzysdk - AdServices - token %@", token);
        NSDictionary *params = @{
            @"adServicesToken": token
        };
        [ZCNetworkManager postWithURL:YZY_AppendUrl(YZY_jl_allinit) Params:params success:^(id responseObject) {
            NSDictionary *surperdic = (NSDictionary *)responseObject;
            NSString *code = [NSString stringWithFormat:@"%@",surperdic[@"code"]];
            if ([code isEqualToString:@"200"]) {
                NSLog(@"yzysdk - 初始化成功");
            }
            
        } failure:^(NSString *error) {
            
        }];
    } else {
        [self performSelector:@selector(yzysdk_init)
                       withObject:nil
                       afterDelay:0.5f];
    }
}

- (void)isAppleVersion {
    [[YZYSaccountStore sharedInstance] saveIsScoreOpen:NO];//默认是关闭的
    
    NSString *gameId = [ZCFunDataFormat GetPlatformGameID];
    NSString *app_Version = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSDictionary *params = @{@"gameId": gameId, @"version": app_Version};
    [ZCNetworkManager postWithURL:YZY_AppendUrl(YZY_getIosVersion) Params:params success:^(id responseObject) {
        NSDictionary *surperdic = (NSDictionary *)responseObject;
        NSString *surpercode = [NSString stringWithFormat:@"%@",surperdic[@"code"]];
        if ([surpercode isEqualToString:@"200"]) {
            NSString *result = [NSString stringWithFormat:@"%@", surperdic[@"data"]];
            if ([result isEqualToString:@"1"]) {
                [[YZYSaccountStore sharedInstance] saveIsScoreOpen:YES];
            }
            
        }
        
    } failure:^(NSString *error) {
        
    }];
    
}


@end
